<?php

session_start();
require_once ('admin/config.php');
if (isset($_GET['action']) && $_GET['action'] == 'thanhtoan') {
    if (isset($_SESSION['cart'])) {
        $pdo = $conn->prepare('INSERT INTO datab_order(customer_name, order_time) VALUES (?, ?)');
        $conn->beginTransaction();
        $pdo->execute(array($_GET['customer_name'], date("Y-m-d H:i:s")));
        if ($pdo->rowCount()) {
            $order_id = $conn->lastInsertId();
            $pdoA = $conn->prepare('INSERT INTO datab_order_product(order_id, product_id, order_quantity) VALUES (?, ?, ?)');
            $arr = unserialize($_SESSION['cart']);
            $product_ids = array_keys($arr);
            foreach ($product_ids as $key) {
                $ar = $arr[$key];
                $pdoA->execute(array($order_id, $ar['id'], $ar['soluong']));
                if (!$pdoA->rowCount()) {
                    $conn->rollBack();
                    $order_id = 0;
                    break;
                }
            }
            if ($order_id) {
                $conn->commit();
                unset($_SESSION['cart']);
            }
        } else {
            $conn->rollBack();
            $order_id = 0;
        }
    }
    header('Location:index.php?order=' . $order_id);
}
?>
